package mysql

import (
	"database/sql"
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"log"
)

//数据库配置
const (
	userName = "root"
	password = "Kibo@2020"
	ip       = "192.168.20.31"
	port     = "3306"
	dbName   = "sellingLicense"
)

// DB Db数据库连接池
var db *sql.DB

// InitDB 注意方法名大写，就是public
func initDB() {
	//构建连接："用户名:密码@tcp(IP:端口)/数据库?charset=utf8"
	path := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8", userName, password, ip, port, dbName)
	//打开数据库,前者是驱动名，所以要导入： _ "github.com/go-sql-driver/mysql"
	db, _ = sql.Open("mysql", path)
	//设置数据库最大连接数
	db.SetConnMaxLifetime(100)
	//设置上数据库最大闲置连接数
	db.SetMaxIdleConns(10)
	//验证连接
	if err := db.Ping(); err != nil {
		log.Println("open database fail")
		return
	}
	log.Println("connect success")
}

func GetDB() *sql.DB {
	if db == nil {
		initDB()
	}
	return db
}
